package com.wx.task.controller;

import com.wx.task.service.AsyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.NamedInheritableThreadLocal;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/hello")
    public String hello() {
        // 这个方法的调用是异步的
        asyncService.hello();
        return "hello() success";
    }

    public static final ThreadLocal<String> inheritableRequestAttributesHolder =
            new InheritableThreadLocal<>();

    @GetMapping("/hi")
    public String hi(String temp) {
        HttpServletRequest request = ((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        System.out.println(request);

        ServletRequestAttributes request12 = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes());

        RequestContextHolder.setRequestAttributes(request12, true);
        System.out.println(request12);

        inheritableRequestAttributesHolder.set(temp);

        System.out.println(inheritableRequestAttributesHolder.get());

        // 这个方法的调用是异步的
        asyncService.hi();
        return "hi() success";
    }
}
